<template>
	<view>
		<u-notify ref="uNotify"></u-notify>
		<view style="display: flex; justify-content:space-between">
			<u-button type="primary" text="添加车辆" @click="add" v-if="user.Roles.indexOf('车辆管理员')!=-1"></u-button>
			<u-button color="rgb(10, 185, 156)" customStyle="fontSize:16px" @click="showAffiliation = true" >车辆所属</u-button>
		</view>
		<u-action-sheet :show="showAffiliation" :actions="dicAffiliation" title="请选择车辆所属" @close="showAffiliation = false"
			@select="affiliationSelect">
		</u-action-sheet>
		<u-search v-model="keyword" :show-action="false" @change="searchlist" placeholder="请输入关键字"></u-search>
		<u-list @scrolltolower="scrolltolower" v-if="carList != false || status == 'loading'">
			<u-list-item v-for="(item, index) in carList" :key="index">
				<u-cell :title="(index+1)+'、'+ item.Name" @click="openpage" :name="item.Id">
					<view slot="label" style="font-size: 12px;color: #909193;line-height: 18px;">
						<span>{{'车牌号:' + (item.CarNo || '') + ' 型号:' + (item.Model || '') + ' 状态:'}}</span>
						<span
							:style="{'color': (item.Status == '空闲' ? 'green' : 'red' )}">{{(item.Status || '')}}</span>
						<span
							:style="{'color': 'red'}"><br>{{(item.Alter != null && item.Alter != '' ? ' 告警:' + item.Alter : '' )}}</span>
					</view>
					<!-- <view slot="right-icon">
						<u-button type="primary" @click.native.stop="toApply(item.Id,item.Name)">申请</u-button>
					</view> -->
					<u-avatar slot="icon" shape="square" size="65"
						:src="item.ImageList[0]? `https://project.gxrunxiang.com/SysFile/download?id=${item.ImageList[0].Id}` : ''"
						customStyle="margin: -3px 5px -3px 0"></u-avatar>
				</u-cell>
				<view style="display: flex; justify-content:space-around">
					<u-button :customStyle="{width: '100px', fontSize: '14px'}" shape="circle" @click='toMaintenance(item.Id)' type="success" size="mini">保养/维修</u-button>
					<u-button :customStyle="{width: '100px', fontSize: '14px'}" shape="circle" @click='toInsurance(item.Id)' type="warning" size="mini">添加保险</u-button>
					<u-button :customStyle="{width: '100px', fontSize: '14px'}" shape="circle" @click='toApply(item.Id,item.Name)' type="primary" size="mini">用车申请</u-button>
				</view>
			</u-list-item>
			<u-loadmore :status="status" v-if="loading" />
			<u-modal :title="'车辆为:' + carName" :show="modalShow"  :closeOnClickOverlay="true"
				@close="modalShow = false,startTime = '',endTime='',remark=''" :showConfirmButton="false">
				<u--form :rules="rules" :model="applyForm" ref="uForm"  labelWidth="auto" labelPosition="top">
					<u-form-item label="预计起始时间"  @click="startTimeShow = true" prop="startTime" disabledColor="#ffffff"><u-input disabled
							v-model="applyForm.startTime" /></u-form-item>
					<u-line color="#999"></u-line>
					<u-form-item label="预计归还时间"  @click="endTimeShow = true" prop="endTime" disabledColor="#ffffff"><u-input disabled
							v-model="applyForm.endTime" /></u-form-item>
					<u-line color="#999"></u-line>
					<u-form-item label="使用地区" prop="range">
						<u-radio-group v-model="applyForm.range" placement="row" @change="rangeChange">
							<u-radio label="市内" name="市内"></u-radio>
							<u-radio label="市外" name="市外"></u-radio>
							<u-radio label="省外" name="省外"></u-radio>
						</u-radio-group>
					</u-form-item >
					<u-line color="#999"></u-line>
					<u-form-item label="事由" prop="remark"><u--textarea v-model="applyForm.remark"
							placeholder="请输入内容"></u--textarea></u-form-item>
					<u-button @click="apply" throttleTime="500"  type="primary">确定</u-button>
				</u--form>
			</u-modal>
			<u-datetime-picker :minDate="theTime" @confirm="changeStartTime" :show="startTimeShow" mode="datetime"
				:closeOnClickOverlay="true" @cancel="startTimeShow = false"></u-datetime-picker>
			<u-datetime-picker :minDate="theTime" @confirm="changeEndTime" :show="endTimeShow" mode="datetime"
				:closeOnClickOverlay="true" @cancel="endTimeShow = false"></u-datetime-picker>
		</u-list>
		<u-empty mode="data" icon="https://project.gxrunxiang.com/cdn/list.png" v-else>
		</u-empty>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/common/config.js'
	import {
		getcarlist,
		addcarapply,
		GetListByParent
	} from '@/common/api.js'
	export default {
		data() {
			return {
				carList: [],
				keyword: "",
				pageIndex: 1, //当前页数
				pageSize: 20, //页数大小
				totalPage: "", //总页数
				total: 0, //数据总数
				status: 'loadmore', //加载状态
				loading: true,
				user: {},
				keyword: "",
				affiliationKey: "",
				userfilter: {},
				dicAffiliation: [{
					name: "所有车辆"
				}],
				modalShow: false,
				startTimeShow: false,
				endTimeShow: false,
				showAffiliation: false,
				carName: "",
				carId: "",
				applyForm: {
					startTime: "",
					endTime: "",
					range: "",
					remark: "",
				},
				notifyData: {
					message: '申请用车成功',
					type: 'success',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 3000,
					safeAreaInsetTop: false
				},
				theTime: new Date().getTime(),
				rules: {
					'startTime': {
						required: true,
						message: '请填写预计起始时间',
						trigger: ['blur']
					},
					'endTime': {
						required: true,
						message: '请填写预计归还时间',
						trigger: ['blur']
					},
					'range': {
						required: true,
						message: '请填写使用地区',
						trigger: ['blur', 'change']
					},
					'remark': {
						required: true,
						message: '请填写事由',
						trigger: ['blur']
					},
				},
			}
		},
		onLoad() {
			this.user = JSON.parse(uni.getStorageSync("$userinfo"))
			GetListByParent("车辆所属", this.dicAffiliation)
		},
		onShow() {
			this.carList = []
			this.pageIndex = 1
			this.getlist()
		},
		onReady() {
				// #ifdef MP-WEIXIN || MP-QQ || MP-BAIDU 
				//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		    	this.$refs.uForm.setRules(this.rules)
				// #endif
		},
		methods: {
			dateFormat(date, fmt = "yyyy年MM月dd日") {
				if (date == null) return null;
				if (typeof date === "string") {
					date = date.slice(0, 19).replace("T", " ").replace(/-/g, "/");
					date = new Date(date);
				} else if (typeof date === "number") {
					date = new Date(date);
				}
				var o = {
					"M+": date.getMonth() + 1,
					"[Dd]+": date.getDate(),
					"h+": date.getHours(),
					"m+": date.getMinutes(),
					"s+": date.getSeconds(),
					"q+": Math.floor((date.getMonth() + 3) / 3),
					S: date.getMilliseconds(),
				};
				if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1
					.length));
				for (var k in o) {
					if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[
						k] : ("00" + o[k]).substr(("" + o[k]).length));
				}
				return fmt;
			},
			openpage(e) {
				uni.navigateTo({
					url: "cardetail?Id=" + e.name
				})
			},
			async getlist() {
				this.status = 'loading'
				// let querytype = this.$route.query.querytype
				let para = {
					Parameters: [],
				}
				if (this.keyword != "") {
					this.userfilter = {
						"ConditionalList": [{
							"Key": 0,
							"Value": {
								"FieldName": "Name",
								"FieldValue": this.keyword,
								"ConditionalType": "Like"
							}
						}, {
							"Key": 1,
							"Value": {
								"FieldName": "CarNo",
								"FieldValue": this.keyword,
								"ConditionalType": "Like"
							}
						}]
					}
					para.jsonPara = JSON.stringify([this.userfilter])
				}
				para.Parameters.push({
					FieldName: "Affiliation",
					ConditionalType: "Like",
					FieldValue: this.affiliationKey,
				})
				para.OrderBys = ['[Alter] desc']
				para.pageSize = this.pageSize
				para.pageIndex = this.pageIndex
				// if (querytype == "日志") {


				// }
				await getcarlist(para).then(res => {
					let data = res.data
					this.carList.push(...data)
					this.total = res.count
					this.totalPage = Math.ceil(this.total / this.pageSize)
				})
				if (this.carList.length < this.pageSize) {
					this.loading = false; //如果数据列表小于当前页数，就让加载标签消失
					this.status = 'nomore';
				} else {
					this.status = 'loadmore';
				}

			},
			scrolltolower() {
				// 如果当前页数大于等于总页数，状态修改为没有更多了，不再继续往下执行代码
				if (this.pageIndex >= this.totalPage) {
					this.status = 'nomore';
					return;
				};
				this.status = 'loading'; //状态改为加载中
				this.pageIndex = ++this.pageIndex; //页面新增一页
				this.getlist(); //修改页数后，重新获取数据
			},
			async searchlist() {
				this.carList = [] //初始化
				this.pageIndex = 1 //初始化当前页数为1
				this.loading = true
				await this.getlist()
			},
			add() {
				uni.navigateTo({
					url: "addcar"
				})
			},
			toApply(Id, Name) {
				this.carName = Name
				this.carId = Id
				this.modalShow = true
			},
			changeStartTime(e) {
				this.applyForm.startTime = this.dateFormat(e.value, 'yyyy年MM月DD日 hh:mm:ss')
				this.startTimeShow = false
			},
			changeEndTime(e) {
				this.applyForm.endTime = this.dateFormat(e.value, 'yyyy年MM月DD日 hh:mm:ss')
				this.endTimeShow = false
			},
			apply() {
				this.$refs.uForm.validate().then(res => {
						addcarapply({
							CarId: this.carId,
							PlanUseTime: this.applyForm.startTime,
							PlanReturnTime: this.applyForm.endTime,
							Range: this.applyForm.range,
							Remark: this.applyForm.remark
						}).then(res => {
								this.$refs.uNotify.show(this.notifyData)
								this.modalShow = false
								setTimeout(() => {
									uni.navigateTo({
										url: "/pages/index/Car/applydetail?Id=" + res + "&isCreated=true"
									})
								}, 1000)
						})
					}).catch(errors => {
						uni.$u.toast('请填写必填参数！')
					})	
			},
			async affiliationSelect(e){
				if(e.name == '所有车辆'){
					this.affiliationKey = ''	
				}else{
					this.affiliationKey = e.name
				}
				this.carList = [] //初始化
				this.pageIndex = 1 //初始化当前页数为1
				this.loading = true
				await this.getlist()
			},
			rangeChange(e) {
				this.applyForm.range = e
			},
			toMaintenance(Id){
				uni.navigateTo({
					url: "addmaintenance?CarId=" + Id
				})
			},
			toInsurance(Id){
				uni.navigateTo({
					url: "addinsurance?CarId=" + Id
				})
			},
		},
	}
</script>

<style>

</style>